package com.link.play.fit.ai.pushWorker

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.link.play.fit.ai.R
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.mealsAlarmCount
import com.link.play.fit.ai.ui.SplashAc
import com.link.play.fit.ai.utils.AppX
import com.link.play.fit.ai.utils.TimeUtils.pmToLocalTime
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class MealsPushWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

    override fun doWork(): Result {
        sendNotification()
        reschedule()
        return Result.success()
    }
    private fun sendNotification() {
        val notifyId = inputData.getString("id")?:""

        mealsAlarmCount+=1
        val channelId = "kcal_meals_channel_id"
        val channelName = "kcal_meals_channel_name"
        val notificationManager =
            applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            channel.setShowBadge(true)
            notificationManager.createNotificationChannel(channel)
        }
        val intent = Intent(applicationContext, SplashAc::class.java)
        val pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        val notification = NotificationCompat.Builder(applicationContext, channelId)
            .setContentTitle("Kcal AI")
            .setContentIntent(pendingIntent)
            .setContentText(applicationContext.getString(R.string.do_you_typically_eat_your_meals_at_the_same_time_every_day))
//            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setSmallIcon(R.mipmap.ic_notification)
            .setColor(applicationContext.getColor(R.color.color_17D995))
            .build()
        notificationManager.notify(notifyId.toInt(), notification)
    }


    private fun reschedule() {
        val targetTime = inputData.getString("TIME")?:""
        val workName = inputData.getString("workName")?:""
        val notifyId = inputData.getString("id")?:""

        val initialDelay = calculateInitialDelay(pmToLocalTime(targetTime))

        val newWork = OneTimeWorkRequestBuilder<MealsPushWorker>()
            .setInitialDelay(initialDelay, TimeUnit.MILLISECONDS).setInputData(
                workDataOf(
                    "TIME" to targetTime,
                    "workName" to workName,
                    "id" to notifyId,
                )
            )
            .build()

        WorkManager.getInstance(AppX.applicationContext)
            .enqueueUniqueWork(
                workName,
                ExistingWorkPolicy.REPLACE,
                newWork
            )
    }


    private fun calculateInitialDelay(targetTime: LocalTime): Long {
        val now = LocalDateTime.now()
        var scheduledTime = now.with(targetTime)

        // 如果当前时间已过目标时间，则调度到明天
        if (scheduledTime.isBefore(now)) {
            scheduledTime = scheduledTime.plusDays(1)
        }

        return ChronoUnit.MILLIS.between(now, scheduledTime)
    }
}